﻿using System;
using System.Linq;
using Fee.Searchers;
using Fee.ViewModel;
using JwtWebApi.Data;
using JwtWebApi.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JwtWebApi.Controllers.Manage
{
    [Authorize]
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class DelegateOrderController : Controller
    {
        private readonly ApplicationDbContext _context;

        public DelegateOrderController(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        [HttpGet("list")]
        public IActionResult Index([FromQuery] DelegateOrderSearch searcher)
        {
            var query = _context.DelegateOrders.Include(f => f.ConstructionTask).ThenInclude(f => f.Station)
                .Where(_ =>
                    searcher.StationName == null || searcher.StationName == _.ConstructionTask.Station.Code
                );

            return Json(new
            {
                data = query.Skip(searcher.GetSkip()).Take(searcher.GetTake()).ToList(),

                total = query.Count()
            });
        }

        [HttpPost("Save")]
        [ModelValidteFilter]
        public IActionResult Save([FromBody] StationViewModel viewModel)

        {
            var sta = viewModel.ToStation(_context);
            if (sta.Id != 0)
                _context.Update(sta);
            else
                _context.Add(sta);

            _context.SaveChanges();
            return Json(new {successed = true, message = "成功", stationId = sta.Id});
        }

        [HttpGet("get/{id}")]
        public IActionResult Get(int id)
        {
            var district = _context.DelegateOrders
                .Include(f => f.ConstructionTask)
                .ThenInclude(f => f.Station)
                .ThenInclude(f => f.District)
                .Include(f => f.Details)
                .ThenInclude(f => f.Project)
                .FirstOrDefault(_ => _.Id == id);
            return Json(district);
        }
    }
}